package com.jiangjiang.eshop.pay.schedule;

import com.jiangjiang.eshop.order.service.OrderService;
import com.jiangjiang.eshop.pay.api.PayApi;
import com.jiangjiang.eshop.pay.api.QueryPayStatusResponse;
import com.jiangjiang.eshop.pay.constant.PayTransactionStatus;
import com.jiangjiang.eshop.pay.constant.PayType;
import com.jiangjiang.eshop.pay.dto.PayTransactionDTO;
import com.jiangjiang.eshop.pay.dto.PayTransactionQueryCondition;
import com.jiangjiang.eshop.pay.service.PayTransactionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author Jianghaowen
 * @Date 2021/9/30
 * @Description: TODO
 * @Version V1.0
 **/
@Slf4j
@Component
public class AlipayStatusQueryTask {

    @Autowired
    private PayTransactionService payTransactionService;

    @Autowired
    private PayApi payApi;

    @Autowired
    private OrderService orderService;

    /**
     * 执行任务
     */
    @Scheduled(fixedRate = 10 * 1000)
    public void execute() {
        try {
            List<PayTransactionDTO> payTransactionDTOList = queryUnpayTransactions();
            for (PayTransactionDTO payTransactionDTO : payTransactionDTOList) {
                QueryPayStatusResponse response = payApi.queryPayStatus(payTransactionDTO.getTransactionChannel(), payTransactionDTO.getOrderNo());
                if(!PayTransactionStatus.UNPAYED.equals(response.getPayTransactionStatus())){
                    payTransactionDTO.setUserPayAccount(response.getUserPayAccount());
                    payTransactionDTO.setTransactionNumber(response.getTransactionNumber());
                    payTransactionDTO.setFinishPayTime(response.getFinishPayTime());
                    payTransactionDTO.setResponseCode(response.getResponseCode());
                    payTransactionDTO.setStatus(response.getPayTransactionStatus());
                    payTransactionService.update(payTransactionDTO);
                    if(PayTransactionStatus.SUCCESS.equals(response.getPayTransactionStatus())) {
                        orderService.informPayOrderSucceed(payTransactionDTO.getOrderInfoId());
                    }
                }
            }

        } catch (Exception e) {
            log.warn("AlipayStatusQueryTask execute error", e);
        }
    }

    private List<PayTransactionDTO> queryUnpayTransactions() {
        PayTransactionQueryCondition condition = PayTransactionQueryCondition.builder()
                .transactionChannel(PayType.ALIPAY)
                .status(PayTransactionStatus.UNPAYED)
                .build();
        // 查询未支付的流水数据
        return payTransactionService.queryByCondition(condition);
    }

}
